﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;

namespace Utility
{
    public class ServerFileHandle
    {
        //private static string ROOT_DIRECTORY = HttpContext.Current.Server.MapPath("~/");
        private static string ROOT_DIRECTORY = @"C:\DroidClaim\root\";
        private static string SERVER_IMAGE_FODER = @"images\";

        public static string CopyImageFile(string sourceFilePath)
        {
            if (sourceFilePath == null || sourceFilePath == "")
            {
                return "";
            }

            //string destFodler = HttpContext.Current.Server.MapPath("~/") + SERVER_IMAGE_FODER;
            string destFodler = ROOT_DIRECTORY + SERVER_IMAGE_FODER;

            if (!System.IO.Directory.Exists(destFodler))
            {
                System.IO.Directory.CreateDirectory(destFodler);
            }

            // get unique file name
            string fileName = System.IO.Path.GetFileNameWithoutExtension(sourceFilePath);
            string ext = System.IO.Path.GetExtension(sourceFilePath);
            fileName = GenerateFileName(fileName) + ext;
            string destFile = System.IO.Path.Combine(destFodler, fileName);

            System.IO.File.Copy(sourceFilePath, destFile);

            return fileName;
        }

        public static string WriteImageFile(string imageString)
        {
            string fileName = "";
            if (imageString == null || imageString == "")
            {
                return fileName;
            }

            Image image = ImageString.Base64ToImage(imageString);
            fileName = GenerateFileName("") + ".jpg";
            string destFodler = ROOT_DIRECTORY + SERVER_IMAGE_FODER;
            string destFile = System.IO.Path.Combine(destFodler, fileName);
            image.Save(destFile, ImageFormat.Jpeg);

            return fileName;
        }

        public static string GetImageString(string imageFilePath)
        {
            if (imageFilePath == null || imageFilePath == "")
            {
                return "";
            }

            string destFodler = ROOT_DIRECTORY + SERVER_IMAGE_FODER;
            string destFile = System.IO.Path.Combine(destFodler, imageFilePath);
            return ImageFileToBase64(destFile);
        }

        public static string ImageFileToBase64(String filePat)
        {
            if (filePat == null || filePat == "")
            {
                return "";
            }

            Image image = Image.FromFile(filePat);
            return ImageString.ImageToBase64(image, ImageFormat.Jpeg);
        }

        public static string GenerateFileName(string context)
        {
            return context + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString();
        }

    }
}